package com.edu.controller;

import com.edu.domain.Menu;
import com.edu.domain.MenuVo;
import com.edu.domain.ResponseResult;
import com.edu.service.MenuService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/menu")
@CrossOrigin("*")
public class MenuController {

    @Autowired
    private MenuService menuService;


    /*
        查询所有菜单信息
     */
    @RequestMapping("/findAllMenu")
    public ResponseResult findAllMenu(MenuVo menuVo){

        PageInfo<Menu> allMenu = menuService.findAllMenu(menuVo);

        return  new ResponseResult(true,200,"查询所有菜单信息成功",allMenu);


    }


    /*
        回显菜单信息
     */

    @RequestMapping("/findMenuInfoById")
    public ResponseResult findMenuInfoById(Integer id){

        // 根据id的值判断当前是更新还是添加操作 判断id的值是否为-1
        if(id == -1){
            // 添加 回显信息中不需要查询menu信息
            List<Menu> subMenuListByPid = menuService.findSubMenuListByPid(-1);

            // 封装数据
            Map<String, Object> map = new HashMap<>();
            map.put("menuInfo",null);
            map.put("parentMenuList",subMenuListByPid);

            return new ResponseResult(true,200,"添加回显成功",map);

        }else {

            //修改操作 回显所有menu信息
             Menu menu =  menuService.findMenuById(id);
            List<Menu> subMenuListByPid = menuService.findSubMenuListByPid(-1);

            // 封装数据
            Map<String, Object> map = new HashMap<>();
            map.put("menuInfo",menu);
            map.put("parentMenuList",subMenuListByPid);

            return new ResponseResult(true,200,"修改回显成功",map);

        }

    }

    /*
        添加&修改菜单
    */
    @RequestMapping("/saveOrUpdateMenu")
    public ResponseResult saveOrUpdateMenu(@RequestBody Menu menu){

        if (menu.getId() == null){
            //添加操作
            menuService.saveMenu(menu);
            return new ResponseResult(true,200,"添加菜单成功",menu);
        }else {
            //修改操作
            menuService.updateMenu(menu);
            return new ResponseResult(true,200,"修改菜单成功",menu);
        }
    }

    /*删除菜单
    * */
    @RequestMapping("/deleteMenu")
    public ResponseResult deleteMenu(Integer id){
        menuService.deleteMenus(id);
        return new ResponseResult(true,200,"删除菜单成功",null);
    }

}
